package com.example.libraryapp.fragment.home;

import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.libraryapp.Constant;
import com.example.libraryapp.R;
import com.example.libraryapp.activity.bookDetail.BookDetailActivity;
import com.example.libraryapp.adapter.BannerImageLoader;
import com.example.libraryapp.adapter.BookAdapter;
import com.example.libraryapp.adapter.base.BaseAdapter;
import com.example.libraryapp.bean.BannerBean;
import com.example.libraryapp.bean.Book;
import com.example.libraryapp.bean.response.BaseResponse;
import com.example.libraryapp.network.base.BaseFragment;
import com.example.libraryapp.widget.CnToolbar;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 伍凯铭
 * @since 2020/6/18
 */
public class HomeFragment extends BaseFragment<HomeContract.View,HomePresenterIml>
        implements HomeContract.View, BaseAdapter.OnItemClickListener, TextView.OnEditorActionListener {

    private BookAdapter mBookAdapter;

    private Banner mBanner;

    @Override
    public void onStart() {
        super.onStart();
        showLoading();
        mPresenter.getBookByCondition("");
        mPresenter.getBanner();
    }

    @Override
    public void onItemClick(View view, int position) {
        Book book = mBookAdapter.getItem(position);
        Intent intent = new Intent(getActivity(), BookDetailActivity.class);
        intent.putExtra(Constant.BOOK_ID,book.getBookId());
        getActivity().startActivity(intent);
    }

    @Override
    public void showAllBook(BaseResponse<List<Book>> response) {
        hideKeyboard();   //收起键盘
        if(response.getResult() != null && !response.getResult().isEmpty()) {
            mBookAdapter.refreshData(response.getResult());
        }else {
            showEmpty();
        }
    }

    @Override
    public void showBanner(BaseResponse<List<BannerBean>> response) {
        List<BannerBean> bannerBeans = response.getResult();
        if(bannerBeans != null) {
            mBanner.setImages(getImagesFromResponse(bannerBeans));
            //banner设置方法全部调用完毕时最后调用
            mBanner.start();
        }
    }

    private List<String> getImagesFromResponse(List<BannerBean> bannerBeans) {
        List<String> result = new ArrayList<>();
        for(BannerBean bannerBean : bannerBeans) {
            result.add(bannerBean.getImgUrl());
        }
        return result;
    }

    @Override
    protected void initView(View view) {
        mBanner = view.findViewById(R.id.banner);
        initBanner();

        RecyclerView recyclerView = view.findViewById(R.id.recycler_view);
        mBookAdapter = new BookAdapter(getContext());
        mBookAdapter.setOnItemClickListener(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext(),RecyclerView.VERTICAL,false));
        recyclerView.setAdapter(mBookAdapter);
        recyclerView.setNestedScrollingEnabled(false);
    }

    private void initBanner() {
        //设置banner样式
        mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        mBanner.setIndicatorGravity(BannerConfig.CENTER);
        //设置图片加载器
        mBanner.setImageLoader(new BannerImageLoader());
        //设置轮播时间
        mBanner.setDelayTime(6000);
        //设置banner动画效果
        mBanner.setBannerAnimation(Transformer.Default);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    protected HomePresenterIml initPresenter() {
        return new HomePresenterIml();
    }

    @Override
    protected void initToolBar(CnToolbar toolbar) {
        //输入框搜索响应
        toolbar.getSearchView().setOnEditorActionListener(this);
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        String condition = mToolbar.getSearchView().getText().toString();
        if(TextUtils.isEmpty(condition)) {
            mPresenter.getBookByCondition("");
        }else {
            mPresenter.getBookByCondition(condition);
        }
        return false;
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     */
    private void hideKeyboard() {
        if(getActivity() != null && getActivity().getCurrentFocus() != null) {
            IBinder token = getActivity().getCurrentFocus().getWindowToken();
            if (token != null) {
                InputMethodManager manager = (InputMethodManager)getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (manager != null) {
                    manager.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        }
    }

    /**
     * @param hidden True代表隐藏，False代表看得见
     */
    @Override
    public void onHiddenChanged(boolean hidden) {
        if(hidden) {
            mBanner.stopAutoPlay();
        }else {
            mBanner.startAutoPlay();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mBanner.stopAutoPlay();
    }

}
